import { useCallback, useMemo, useEffect } from 'react';
import { useContextSelector } from 'use-context-selector';

import { UserRoleEnum } from '@/common/app/constants';
import { t } from '@/locales/i18n';
import { useRouter } from '@/router/hooks';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { AppTypeEnum } from '@/types/app/type';

import { AppContext, TabEnum } from '../../../context';

function RouteTab(): JSX.Element {
  const router = useRouter();
  const { currentTab, preview } = useContextSelector(AppContext, (v) => v);
  const { appDetail } = useOrchestrationStore();

  const { userRole } = useOrchestrationStore();

  const setCurrentTab = useCallback(
    (tab: TabEnum) => {
      const searchParams = new URLSearchParams(window.location.search);
      searchParams.set('currentTab', tab);
      console.log(searchParams.toString());

      const url = `/app/workflow?${searchParams.toString()}`;
      router.replace(url);
    },
    [router],
  );

  const getAdminTabs = useCallback(() => {
    const baseTabs = [
      { label: t('setting_app'), id: TabEnum.appEdit },
      { label: t('knowledge_manage'), id: TabEnum.knowledge },
    ];

    // 插件仅显示编排、知识管理、应用看板、应用测试
    if (appDetail.appType === AppTypeEnum.plugin) {
      return [
        ...baseTabs,
        { label: t('report_manage'), id: TabEnum.reporte },
        { label: t('report_test'), id: TabEnum.test },
      ];
    }

    return [
      ...baseTabs,
      { label: t('permission_manage'), id: TabEnum.permission },
      { label: t('share'), id: TabEnum.share },
      { label: t('report_manage'), id: TabEnum.reporte },
      { label: t('report_test'), id: TabEnum.test },
    ];
  }, [appDetail.appType]);

  const getNonAdminTabs = useCallback(() => {
    return [{ label: t('knowledge_manage'), id: TabEnum.knowledge }];
  }, []);

  const tabList = useMemo(() => {
    // 预览模式下的tab
    if (currentTab === TabEnum.preview) {
      return [
        {
          label: '预览',
          id: TabEnum.preview,
        },
      ];
    }

    // 根据用户角色返回对应的tab列表
    return userRole === UserRoleEnum.admin ? getAdminTabs() : getNonAdminTabs();
  }, [currentTab, userRole, getAdminTabs, getNonAdminTabs]);

  useEffect(() => {
    // 如果当前tab不在tabList中，则设置为第一个有权限的tab
    if (tabList.length > 0 && !tabList.some((tab) => tab.id === currentTab)) {
      setCurrentTab(tabList[0].id);
    }
  }, [currentTab, tabList, appDetail.appType, setCurrentTab]);

  useEffect(() => {
    if (preview) {
      return;
    }

    if (!currentTab) {
      if (userRole === UserRoleEnum.admin) {
        setCurrentTab(TabEnum.appEdit);
      } else if (userRole === UserRoleEnum.knowledge_manager) {
        setCurrentTab(TabEnum.knowledge);
      }
    }
  }, [userRole, preview, currentTab, setCurrentTab]);

  return (
    <div className="flex h-full space-x-4 whitespace-nowrap">
      {tabList.map((tab) => (
        <div
          className={`flex h-full flex-col items-center justify-center border-b-[3px] px-2 py-1 text-base ${
            currentTab === tab.id
              ? 'border-@brand-color font-font-weight-600 text-@brand-color'
              : 'cursor-pointer border-[#ffffff00] text-text-4 hover:text-@brand-color'
          }`}
          key={tab.id}
          {...(currentTab === tab.id
            ? {}
            : {
                onClick: () => setCurrentTab(tab.id),
              })}
        >
          <div className="mt-2">{tab.label}</div>
        </div>
      ))}
    </div>
  );
}

export default RouteTab;
